package com.example.suntest.service2;

import com.example.suntest.entity.User;
import com.example.suntest.entity.UserDTO;
import com.example.suntest.entity.UserVO;
import lombok.Getter;

import java.lang.reflect.Constructor;

/**
 * @version 1.0
 * @Package: com.example.suntest.enums
 * @ClassName: ConvertStrategy
 * @Author: sgq
 * @Date: 2024/7/10 16:14
 * @Description: TODD
 */
@Getter
public enum PushDownConvertStrategy {

    USER_TO_USER_DTO(User.class, UserDTO.class),
    USER_TO_USER_VO(User.class, UserVO.class);

    /**
     * 源类型
     */
    private Class<?> sourceType;
    /**
     * 目标类型
     */
    private Class<?> targetType;
    /**
     * 转换器
     */
    private PushDownConverter<?, ?> converter;

    PushDownConvertStrategy(Class<?> sourceType, Class<?> targetType) {
        this.sourceType = sourceType;
        this.targetType = targetType;
    }

    public synchronized <S, T> PushDownConverter<S, T> getConverter() {
        if (converter == null) {
            try {
                // 构建实现类的全限定名
                String converterClassName =  "com.example.suntest.service2." +
                        sourceType.getSimpleName() + "To" + targetType.getSimpleName() + "PushDownConverter";
                // 加载实现类
                Class<?> converterClass = Class.forName(converterClassName);
                // 确保实现类是PushDownConverter的子类
                if (PushDownConverter.class.isAssignableFrom(converterClass)) {
                    // 获取构造函数并实例化，假设构造函数接受两个Class参数
                    Constructor<?> constructor = converterClass.getConstructor();
                    converter = (PushDownConverter<S, T>) constructor.newInstance();
                } else {
                    throw new RuntimeException("类 " + converterClassName + " 没有实现PushDownConverter接口");
                }
            } catch (Exception e) {
                throw new RuntimeException("实现类不存在，请创建后再试！");
            }
        }
        // 需要注意的是，这里返回的类型是擦除后的类型，但在构造时已经指定了具体类型
        return (PushDownConverter<S, T>) converter;
    }
}
